package com.thz.admin.controller.matting;

import com.thz.common.dto.matting.ConversionImageMattingRequestDTO;
import com.thz.common.dto.matting.ConversionImageMattingResponseDTO;
import com.thz.common.result.Result;
import com.thz.common.utils.IpUtils;
import com.thz.system.service.matting.IConversionImageMattingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片抠图控制器
 * 
 * @author THZ
 * @date 2025
 */
@Slf4j
@RestController
@RequestMapping("/api/conversion/imageMatting")
@Tag(name = "图片抠图", description = "图片抠图相关接口")
public class ConversionImageMattingController {
    
    @Autowired
    private IConversionImageMattingService conversionService;
    
    /**
     * 上传图片并执行抠图（同步模式）
     * 
     * @param file 图片文件
     * @param algorithm 抠图算法（u2net, u2netp, u2net_human_seg, u2net_cloth_seg, silueta等）
     * @param backgroundColor 背景颜色（transparent表示透明背景，或RGB颜色值如#FFFFFF）
     * @param width 输出宽度（可选）
     * @param height 输出高度（可选）
     * @param keepAspectRatio 是否保持宽高比（默认true）
     * @param quality 输出质量（1-100，默认95）
     * @param featherEdge 是否羽化边缘（默认false）
     * @param featherRadius 羽化半径（像素，默认0）
     * @param request HTTP请求对象
     * @return 转换结果
     */
    @PostMapping("/upload")
    @Operation(summary = "上传图片并执行抠图（同步）", description = "上传图片文件，同步移除背景并生成透明PNG")
    public Result<ConversionImageMattingResponseDTO> uploadAndConvert(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "algorithm", required = false, defaultValue = "u2net") String algorithm,
            @RequestParam(value = "backgroundColor", required = false, defaultValue = "transparent") String backgroundColor,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "height", required = false) Integer height,
            @RequestParam(value = "keepAspectRatio", required = false, defaultValue = "true") Boolean keepAspectRatio,
            @RequestParam(value = "quality", required = false, defaultValue = "95") Integer quality,
            @RequestParam(value = "featherEdge", required = false, defaultValue = "false") Boolean featherEdge,
            @RequestParam(value = "featherRadius", required = false, defaultValue = "0") Integer featherRadius,
            HttpServletRequest request) {
        
        log.info("收到图片抠图请求（同步）: filename={}, size={}, contentType={}, algorithm={}, backgroundColor={}", 
                file.getOriginalFilename(), file.getSize(), file.getContentType(), algorithm, backgroundColor);
        
        // 快速验证文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("上传文件不能为空");
        }
        
        // 构建请求参数
        ConversionImageMattingRequestDTO requestDTO = new ConversionImageMattingRequestDTO();
        requestDTO.setAlgorithm(algorithm);
        requestDTO.setBackgroundColor(backgroundColor);
        requestDTO.setWidth(width);
        requestDTO.setHeight(height);
        requestDTO.setKeepAspectRatio(keepAspectRatio);
        requestDTO.setQuality(quality);
        requestDTO.setFeatherEdge(featherEdge);
        requestDTO.setFeatherRadius(featherRadius);
        
        // 获取客户端IP
        String ipAddress = IpUtils.getClientIp(request);
        
        // 执行抠图转换（同步）
        ConversionImageMattingResponseDTO responseDTO = conversionService.convertImageMatting(
                file, requestDTO, ipAddress, null);
        
        return Result.success("图片抠图成功", responseDTO);
    }
    
    /**
     * 上传图片并执行抠图（异步模式）
     * 立即返回任务ID，后台异步处理，客户端需要轮询查询任务状态
     * 
     * @param file 图片文件
     * @param algorithm 抠图算法（u2net, u2netp, u2net_human_seg, u2net_cloth_seg, silueta等）
     * @param backgroundColor 背景颜色（transparent表示透明背景，或RGB颜色值如#FFFFFF）
     * @param width 输出宽度（可选）
     * @param height 输出高度（可选）
     * @param keepAspectRatio 是否保持宽高比（默认true）
     * @param quality 输出质量（1-100，默认95）
     * @param featherEdge 是否羽化边缘（默认false）
     * @param featherRadius 羽化半径（像素，默认0）
     * @param request HTTP请求对象
     * @return 任务ID和初始状态
     */
    @PostMapping("/uploadAsync")
    @Operation(summary = "上传图片并执行抠图（异步）", description = "异步模式，立即返回任务ID，后台处理，客户端轮询查询进度")
    public Result<ConversionImageMattingResponseDTO> uploadAndConvertAsync(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "algorithm", required = false, defaultValue = "u2net") String algorithm,
            @RequestParam(value = "backgroundColor", required = false, defaultValue = "transparent") String backgroundColor,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "height", required = false) Integer height,
            @RequestParam(value = "keepAspectRatio", required = false, defaultValue = "true") Boolean keepAspectRatio,
            @RequestParam(value = "quality", required = false, defaultValue = "95") Integer quality,
            @RequestParam(value = "featherEdge", required = false, defaultValue = "false") Boolean featherEdge,
            @RequestParam(value = "featherRadius", required = false, defaultValue = "0") Integer featherRadius,
            HttpServletRequest request) {
        
        log.info("收到图片抠图请求（异步）: filename={}, size={}, contentType={}, algorithm={}, backgroundColor={}", 
                file.getOriginalFilename(), file.getSize(), file.getContentType(), algorithm, backgroundColor);
        
        // 快速验证文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("上传文件不能为空");
        }
        
        // 构建请求参数
        ConversionImageMattingRequestDTO requestDTO = new ConversionImageMattingRequestDTO();
        requestDTO.setAlgorithm(algorithm);
        requestDTO.setBackgroundColor(backgroundColor);
        requestDTO.setWidth(width);
        requestDTO.setHeight(height);
        requestDTO.setKeepAspectRatio(keepAspectRatio);
        requestDTO.setQuality(quality);
        requestDTO.setFeatherEdge(featherEdge);
        requestDTO.setFeatherRadius(featherRadius);
        
        // 获取客户端IP
        String ipAddress = IpUtils.getClientIp(request);
        
        // 执行抠图转换（异步）
        ConversionImageMattingResponseDTO responseDTO = conversionService.convertImageMattingAsync(
                file, requestDTO, ipAddress, null);
        
        return Result.success("抠图任务已提交，请使用返回的ID查询进度", responseDTO);
    }
    
    /**
     * 上传手动抠图结果
     * 
     * @param file 手动编辑后的图片文件
     * @param recordId 要更新的记录ID
     * @param replaceMode 是否为替换模式（true=更新原记录，false=创建新记录）
     * @param request HTTP请求对象
     * @return 转换结果
     */
    @PostMapping("/uploadManual")
    @Operation(summary = "上传手动抠图结果", description = "上传用户手动编辑后的抠图结果")
    public Result<ConversionImageMattingResponseDTO> uploadManualMattingResult(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "recordId", required = false) Long recordId,
            @RequestParam(value = "replaceMode", required = false, defaultValue = "true") Boolean replaceMode,
            HttpServletRequest request) {
        
        log.info("收到手动抠图结果上传请求: filename={}, size={}, contentType={}, recordId={}, replaceMode={}", 
                file.getOriginalFilename(), file.getSize(), file.getContentType(), recordId, replaceMode);
        
        // 快速验证文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("上传文件不能为空");
        }
        
        // 获取客户端IP
        String ipAddress = IpUtils.getClientIp(request);
        
        // 执行手动抠图结果保存/更新
        ConversionImageMattingResponseDTO responseDTO;
        if (replaceMode != null && replaceMode && recordId != null) {
            // 替换模式：更新原记录
            responseDTO = conversionService.updateManualMattingResult(file, recordId, ipAddress);
        } else {
            // 创建模式：创建新记录
            responseDTO = conversionService.saveManualMattingResult(file, recordId, ipAddress);
        }
        
        return Result.success("手动抠图结果保存成功", responseDTO);
    }
    
    /**
     * 查询转换记录
     * 
     * @param id 记录ID
     * @return 转换记录
     */
    @GetMapping("/{id:\\d+}")
    @Operation(summary = "查询转换记录", description = "根据ID查询转换记录详情")
    public Result<ConversionImageMattingResponseDTO> getConversionDetail(@PathVariable Long id) {
        ConversionImageMattingResponseDTO responseDTO = conversionService.getConversionDetail(id);
        return Result.success(responseDTO);
    }
}



